import type { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import router from "@/router";

import MenuAPI, { type RouteVO } from "@/api/system/menu";
import { getMenus } from "@/api/menu/menu";
// import { MenuListData } from "@/api/menu/type";
import { buildTree } from "@/utils/treeUtil";
const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

type leftMenus = RouteRecordRaw & {
  isButton: number;
};

export const usePermissionStore = defineStore("permission", () => {
  // 所有路由，包括静态和动态路由
  const routes = ref<RouteRecordRaw[]>([]);
  // 混合模式左侧菜单
  const mixLeftMenus = ref<RouteRecordRaw[]>([]);
  // 路由是否已加载
  const isRoutesLoaded = ref(false);

  const menuFilters = (list: leftMenus[]) => {
    let _list: leftMenus[] = [];
    list.forEach((item) => {
      if (item.isButton == 0) {
        if (item.children?.length) {
          item.children = menuFilters(item.children as leftMenus[]);
        }
        _list.push(item);
      }
    });
    return _list;
  };

  /**
   * 生成动态路由
   */
  function generateRoutes() {
    // let res=await getMenus();
    // console.log('999122',res.list);

    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      getMenus()
        .then((data) => {
          // console.log("data11", data.list);
          console.log("data", data.list);

          let list = data.list
            .filter((item) => item.url)
            .map((item) => ({
              id: item.id,
              pid: item.pid,
              isButton: item.isButton,
              path: (item.pid == 0 ? "/" : "") + item.url,
              component: item.pid == 0 ? "Layout" : item.pathName,
              name: item.url + item.id,
              meta: {
                title: item.name,
                icon: item.icon,
              },
            }));

          let _list: RouteVO[] = buildTree(list);
          console.log(123, list);

          const dynamicRoutes = transformRoutes(_list, "");
          let leftMenu = menuFilters(JSON.parse(JSON.stringify(dynamicRoutes)));
          // const dynamicRoutes = transformRoutes(data);

          // console.log(112233, leftMenu);

          routes.value = constantRoutes.concat(leftMenu);
          isRoutesLoaded.value = true;
          resolve(dynamicRoutes);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 混合模式菜单下根据顶部菜单路径设置左侧菜单
   *
   * @param topMenuPath - 顶部菜单路径
   */
  const setMixLeftMenus = (topMenuPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === topMenuPath);
    if (matchedItem && matchedItem.children) {
      mixLeftMenus.value = matchedItem.children;
    }
  };

  /**
   * 重置路由
   */
  const resetRouter = () => {
    // 删除动态路由，保留静态路由
    routes.value.forEach((route) => {
      if (route.name && !constantRoutes.find((r) => r.name === route.name)) {
        // 从 router 实例中移除动态路由
        router.removeRoute(route.name);
      }
    });

    routes.value = [];
    mixLeftMenus.value = [];
    isRoutesLoaded.value = false;
  };

  return {
    routes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
    isRoutesLoaded,
    resetRouter,
  };
});

/**
 * 转换路由数据为组件
 */
const transformRoutes = (routes: RouteVO[], parentUrl: string) => {
  const asyncRoutes: RouteRecordRaw[] = [];
  routes.forEach((route) => {
    const tmpRoute = { ...route } as RouteRecordRaw;
    // 顶级目录，替换为 Layout 组件
    if (tmpRoute.component?.toString() == "Layout") {
      tmpRoute.component = Layout;
    } else {
      // 其他菜单，根据组件路径动态加载组件
      // console.log(111111111111, `../../views/${parentUrl}/${tmpRoute.component}.vue`);

      const component = modules[`../../views/${parentUrl}/${tmpRoute.component}.vue`];
      if (component) {
        tmpRoute.component = component;
      } else {
        tmpRoute.component = modules["../../views/error-page/404.vue"];
      }
    }

    if (tmpRoute.children) {
      let pUrl = route.path ? route.path?.replace("/", "") : "";
      tmpRoute.children = transformRoutes(route.children, pUrl);
    }

    asyncRoutes.push(tmpRoute);
  });

  return asyncRoutes;
};

/**
 * 在组件外使用 Pinia store 实例 @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
